// history.js
const app = getApp();

Page({
  data: {
    historyList: [], // 历史记录列表
    isEmpty: true, // 是否为空
    isLoading: false, // 是否正在加载
    currentVideoUrl: '',
    showVideoPlayer: false,
    videoTitle: '视频播放',
    shareItem: null // 当前要分享的项目
  },

  onLoad() {
    // 使用setTimeout确保页面已经完全加载后再调用API
    setTimeout(() => {
      this.loadHistoryData();
    }, 300);
  },
  
  onShow() {
    // 页面显示时刷新历史数据
    setTimeout(() => {
      this.loadHistoryData();
    }, 300);
  },
  
  // 加载历史记录数据
  loadHistoryData() {
    this.setData({ isLoading: true });
    
    const historyList = wx.getStorageSync('watermarkHistory') || [];
    
    // 处理历史记录中可能的undefined值
    const processedList = historyList.map(item => {
      return {
        ...item,
        title: item.title || '无标题内容',
        createdAt: item.createdAt || '未知时间'
      };
    });
    
    this.setData({
      historyList: processedList,
      isEmpty: processedList.length === 0,
      isLoading: false
    });
  },
  
  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有历史记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          wx.setStorageSync('watermarkHistory', []);
          this.setData({
            historyList: [],
            isEmpty: true
          });
          
          wx.showToast({
            title: '历史记录已清空',
            icon: 'success'
          });
        }
      }
    });
  },
  
  // 删除单个历史记录
  deleteHistoryItem(e) {
    const id = e.currentTarget.dataset.id;
    
    let historyList = this.data.historyList;
    const updatedList = historyList.filter(item => item.id !== id);
    
    // 更新存储和UI
    wx.setStorageSync('watermarkHistory', updatedList);
    this.setData({
      historyList: updatedList,
      isEmpty: updatedList.length === 0
    });
    
    wx.showToast({
      title: '已删除',
      icon: 'success'
    });
  },
  
  // 查看历史记录项详情
  viewHistoryItem(e) {
    const item = e.currentTarget.dataset.item;
    
    // 根据类型不同进行不同处理
    if (item.type === 'image') {
      // 查看图片
      wx.previewImage({
        urls: [item.url],
        current: item.url
      });
    } else {
      // 打开视频播放器模态框
      this.setData({
        currentVideoUrl: item.url,
        showVideoPlayer: true,
        videoTitle: item.title || '视频播放'
      });
    }
  },

  // Navigate to home page - can be used by both function names
  navigateToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  
  // Alias for navigateToHome for backward compatibility
  goToHome() {
    this.navigateToHome();
  },

  // Preview media (image or video)
  previewMedia(e) {
    const item = e.currentTarget.dataset.item;
    
    if (item.type === 'image') {
      wx.previewImage({
        urls: [item.url],
        current: item.url
      });
    } else if (item.type === 'video') {
      // 改为直接在小程序内播放
      this.setData({
        currentVideoUrl: item.url,
        showVideoPlayer: true,
        videoTitle: item.title || '视频播放'
      });
    }
  },

  // Download history item again
  downloadAgain(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.historyList.find(item => item.id === id);
    
    if (!item) return;
    
    wx.showLoading({
      title: '下载中...',
    });
    
    if (item.type === 'image') {
      wx.downloadFile({
        url: item.url,
        success: (res) => {
          if (res.statusCode === 200) {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                wx.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                });
              },
              fail: (err) => {
                console.error('Save Error:', err);
                wx.showToast({
                  title: '保存失败，请授权相册权限',
                  icon: 'none'
                });
              }
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    } else if (item.type === 'video') {
      wx.downloadFile({
        url: item.url,
        success: (res) => {
          if (res.statusCode === 200) {
            wx.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                wx.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                });
              },
              fail: (err) => {
                console.error('Save Error:', err);
                wx.showToast({
                  title: '保存失败，请授权相册权限',
                  icon: 'none'
                });
              }
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    }
  },

  // Share function
  onShareAppMessage(e) {
    console.log('分享事件触发', e, this.data.shareItem);
    
    // 检查是否有记录的分享项目
    if (this.data.shareItem) {
      const item = this.data.shareItem;
      
      // 清除记录的分享项目
      setTimeout(() => {
        this.setData({ shareItem: null });
      }, 300);
      
      // 根据类型返回不同分享内容
      if (item.type === 'image') {
        return {
          title: item.title || '分享一张无水印图片给您',
          path: '/pages/index/index?source=history',
          imageUrl: item.url || '/images/share_image.png'
        };
      } else {
        return {
          title: item.title || '分享一个无水印视频给您',
          path: '/pages/index/index?source=history',
          imageUrl: item.cover || '/images/share_image.png'
        };
      }
    }
    
    // 默认分享内容
    return {
      title: '【】一键去除视频/图片水印，高清无损！',
      path: '/pages/index/index',
      imageUrl: '/images/share_image.png'
    };
  },

  // Close video player
  closeVideoPlayer() {
    this.setData({
      showVideoPlayer: false,
      currentVideoUrl: ''
    });
  },
  
  // Stop event propagation
  stopPropagation(e) {
    // Prevent event bubbling
    return false;
  },
  
  // Handle video error
  handleVideoError(e) {
    console.error('视频播放错误:', e.detail);
    wx.showModal({
      title: '视频播放错误',
      content: '视频播放失败，可能是视频格式不支持或链接已失效。您可以尝试保存到相册后查看。',
      confirmText: '保存视频',
      cancelText: '关闭',
      success: (res) => {
        if (res.confirm) {
          this.saveCurrentVideo();
        } else {
          this.closeVideoPlayer();
        }
      }
    });
  },
  
  // Save current playing video
  saveCurrentVideo() {
    const { currentVideoUrl } = this.data;
    console.log('currentVideoUrl', currentVideoUrl);
    if (!currentVideoUrl) return;
    
    wx.showLoading({
      title: '正在下载...',
      mask: true
    });
    
    wx.downloadFile({
      url: currentVideoUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.hideLoading();
          wx.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '已保存到相册',
                icon: 'success'
              });
              this.closeVideoPlayer();
            },
            fail: (err) => {
              console.error('保存失败:', err);
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 点击单个项目的分享按钮
  onShareItem(e) {
    const item = e.currentTarget.dataset.item;
    console.log('准备分享项目:', item);
    this.setData({
      shareItem: item
    });
    // 注意：这个函数只是记录要分享的内容
    // 真正的分享会由系统触发onShareAppMessage
  },
}); 